<?php defined('BASEPATH') OR exit('No direct script access allowed');

class uploking_folders_m extends MY_Model {
	public function get_page_tree($userId)
	{
		$all_pages = $this->db
		->select('id, parent_id, name')
		->where('user_id', $userId)
		->order_by('`order`')
		->get('uploking_folders')
		->result_array();

		if(!$all_pages){
			return array();
		}
		
		// we must reindex the array first
		foreach ($all_pages as $row)
		{
			$pages[$row['id']] = $row;
		}

		unset($all_pages);

		// build a multidimensional array of parent > children
		foreach ($pages as $row)
		{
			if (array_key_exists($row['parent_id'], $pages))
			{
				// add this page to the children array of the parent page
				$pages[$row['parent_id']]['children'][] =& $pages[$row['id']];
			}
				
			// this is a root page
			if ($row['parent_id'] == 0)
			{
				$page_array[] =& $pages[$row['id']];
			}
		}

		return $page_array;
	}
	public function _set_children($page)
	{
		if (isset($page['children']))
		{
			foreach ($page['children'] as $i => $child)
			{
				$this->db->where('id', str_replace('page_', '', $child['id']));
				$this->db->update('uploking_folders', array('parent_id' => str_replace('page_', '', $page['id']), '`order`' => $i));
				
				//repeat as long as there are children
				if (isset($child['children']))
				{
					$this->_set_children($child);
				}
			}
		}
	}
	public function update_lookup($root_pages)
	{
		// first reset the URI of all root pages
		$this->db
			->where('parent_id', 0)
			->set('uri', 'slug', FALSE)
			->update('uploking_folders');
			
		foreach ($root_pages as $page)
		{
			$this->reindex_descendants($page);
		}
	}
	public function build_lookup($id)
	{
		$current_id = $id;
	
		$segments = array();
		do
		{
			$page = $this->db
				->select('slug, parent_id')
				->where('id', $current_id)
				->get('uploking_folders')
				->row();
	
			$current_id = $page->parent_id;
			array_unshift($segments, $page->slug);
		}
		while( $page->parent_id > 0 );
	
		// If the URI has been passed as a string, explode to create an array of segments
		return parent::update($id, array(
			'uri' => implode('/', $segments)
		));
	}
	public function reindex_descendants($id)
	{
		$descendants = $this->get_descendant_ids($id);
		foreach ($descendants as $descendant)
		{
			//$this->build_lookup($descendant);
		}
	}
}
?>